#include "ffmpegutil.h"
#include <QDebug>
extern "C" {

    #include <libswscale/swscale.h>
    #include <libavutil/imgutils.h>
}

FFmpegUtil::FFmpegUtil()
{

}

void FFmpegUtil::convertRawVideo(RawVideoFrame &inVideoFrame, RawVideoFrame &outVideoFrame)
{

    SwsContext* context = nullptr;
    // 输入输出缓存
    uint8_t* inData[4],* outData[4];
    // 每个平面的大小
    int inStrides[4], outStriders[4];

    int inFrameSize, outFrameSize;


    int ret = 0;

    context = sws_getContext(inVideoFrame.width,inVideoFrame.height,inVideoFrame.format,
                             outVideoFrame.width,outVideoFrame.height,outVideoFrame.format,
                             SWS_BILINEAR,nullptr,nullptr,nullptr);

    if(context == nullptr) {


        outVideoFrame.data = nullptr;
        return;
    }

    ret = av_image_alloc(inData,inStrides,inVideoFrame.width,inVideoFrame.height,inVideoFrame.format,1);

    if(ret < 0) {

        sws_freeContext(context);
        qDebug() << "av_image_alloc fail";
        return;
    }

   ret = av_image_alloc(outData,outStriders,outVideoFrame.width,outVideoFrame.height,outVideoFrame.format,1);

   inFrameSize = av_image_get_buffer_size(inVideoFrame.format,inVideoFrame.width,inVideoFrame.height,1);

   outFrameSize = av_image_get_buffer_size(outVideoFrame.format,outVideoFrame.width,outVideoFrame.height,1);

   memcpy(inData[0],inVideoFrame.data,inFrameSize);

   sws_scale(context,inData,inStrides,0,inVideoFrame.height,outData,outStriders);

   outVideoFrame.data = (char*)malloc(outFrameSize);

   memcpy(outVideoFrame.data,outData[0],outFrameSize);

   av_freep(&inData[0]);
   av_freep(&outData[0]);
   sws_freeContext(context);
}
